package com.jhgsys.internal.incentive.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.incentive.constant.IncentiveRewardConstant;
import com.jhgsys.internal.incentive.dto.IncentiveRewardApplyDto;
import com.jhgsys.internal.incentive.entity.IncentiveRewardApply;
import com.jhgsys.internal.incentive.service.IIncentiveRewardApplyService;
import com.jhgsys.internal.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.Date;
import java.util.Map;

/**
 * 安全奖励审核 Controller
 *
 * @author wanghjw
 * @date 2024-09-03 14:08:36
 */
@Slf4j
@Validated
@Controller
public class IncentiveRewardAuditController extends BaseController {

    @Autowired
    private IIncentiveRewardApplyService incentiveRewardApplyService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "incentiveRewardAudit")
    @RequiresPermissions("incentiveRewardAudit:view")
    public String incentiveRewardAuditIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("incentive/incentiveRewardAudit/incentiveRewardAuditList");
    }



    @GetMapping(FebsConstant.VIEW_PREFIX + "incentiveRewardAudit/audit/{id}")
    @RequiresPermissions("incentiveRewardAudit:audit")
    public String incentiveRewardAuditUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        IncentiveRewardApplyDto dto = incentiveRewardApplyService.findIncentiveRewardApplyById(id);
        model.addAttribute("incentiveRewardAudit", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        return FebsUtil.view("incentive/incentiveRewardAudit/incentiveRewardAuditEdit");
    }


    /**
     * 查询（分页）
     * @author wanghjw
     * @date 2024-09-03 14:08:36
     */
    @GetMapping("incentiveRewardAudit/list")
    @ResponseBody
    @RequiresPermissions("incentiveRewardAudit:view")
    public FebsResponse incentiveRewardApplyList(QueryRequest request, IncentiveRewardApplyDto incentiveRewardApply) {
        Map<String, Object> dataTable = getDataTable(this.incentiveRewardApplyService.findIncentiveRewardApplyPage(request, incentiveRewardApply));
        return new FebsResponse().success().data(dataTable);
    }




    /**
     * 审核 安全奖励申请
     * @author wanghjw
     * @date 2024-09-03 14:08:36
     */
    @Log("审核安全奖励申请")
    @PostMapping("incentiveRewardAudit/audit")
    @ResponseBody
    @RequiresPermissions("incentiveRewardAudit:audit")
    public FebsResponse updateIncentiveRewardApply(@RequestBody IncentiveRewardApplyDto incentiveRewardApply) throws FebsException {
        checkParams(incentiveRewardApply);
        try {
            IncentiveRewardApply queryData = this.incentiveRewardApplyService.findIncentiveRewardApplyById(incentiveRewardApply.getRewardApplyId());
            if(ObjectUtils.isEmpty(queryData)){
                return new FebsResponse().fail().message("找不到待审核记录");
            }
            if(!IncentiveRewardConstant.APPLY_STATUS.WAIT_AUDIT.equals(queryData.getStatus()) &&
                    !IncentiveRewardConstant.APPLY_STATUS.FAIL_ISSUANCE.equals(queryData.getStatus())){
                return new FebsResponse().fail().message("该申请无法被审核，请刷新后重试");
            }
            incentiveRewardApply.setAuditUserId(getCurrentUserId());
            incentiveRewardApply.setAuditRealName(getCurrentUser().getUname());
            incentiveRewardApply.setAuditDate(new Date());
            incentiveRewardApply.setUpdatedBy(getCurrentUser().getUserName());
            incentiveRewardApply.setUpdatedTime(new Date());
            incentiveRewardApply.setRewardGoodsFlg(null);
            incentiveRewardApply.setRewardAmountFlg(null);
            incentiveRewardApply.setRewardScoreFlg(null);
            this.incentiveRewardApplyService.auditIncentiveRewardApply(incentiveRewardApply,queryData.getStatus(), getCurrentUser());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "审核安全奖励申请失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    private void checkParams(IncentiveRewardApplyDto incentiveRewardApply) throws FebsException {

        if(StringUtils.isBlank(incentiveRewardApply.getStatus())){
            throw new FebsException("状态不能为空");
        }

        if(StringUtils.isBlank(incentiveRewardApply.getRewardApplyId())){
            throw new FebsException("奖励ID不能为空");
        }

        if(StringUtils.isBlank(incentiveRewardApply.getAuditRemark())){
            throw new FebsException("审核意见不能为空");
        }

    }

}
